import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns

# 设置随机种子确保可重复性
np.random.seed(0)

# 生成虚拟数据集
n = 200  # 数据量
data = pd.DataFrame({
    'Feature1': np.random.normal(50, 10, n),  # 正态分布数据
    'Feature2': np.random.normal(30, 5, n)    # 正态分布数据
})

# 随机引入缺失值
missing_rate = 0.2
data.loc[data.sample(frac=missing_rate).index, 'Feature1'] = np.nan
data.loc[data.sample(frac=missing_rate).index, 'Feature2'] = np.nan

# 随机填补缺失值
data_imputed = data.copy()
for col in data_imputed.columns:
    missing = data_imputed[col].isnull()
    data_imputed.loc[missing, col] = np.random.choice(data_imputed[col].dropna(), size=missing.sum())

# 设置绘图风格
sns.set(style="whitegrid")
plt.figure(figsize=(16, 10))

# 1. 缺失值填补前后的直方图
plt.subplot(2, 2, 1)
sns.histplot(data['Feature1'], color='blue', kde=True, label='Original (Feature1)', alpha=0.6, bins=15)
sns.histplot(data_imputed['Feature1'], color='orange', kde=True, label='Imputed (Feature1)', alpha=0.6, bins=15)
plt.title("Distribution Before and After Imputation (Feature1)")
plt.legend()

plt.subplot(2, 2, 2)
sns.histplot(data['Feature2'], color='green', kde=True, label='Original (Feature2)', alpha=0.6, bins=15)
sns.histplot(data_imputed['Feature2'], color='red', kde=True, label='Imputed (Feature2)', alpha=0.6, bins=15)
plt.title("Distribution Before and After Imputation (Feature2)")
plt.legend()

# 2. 缺失值填补前后的箱线图
plt.subplot(2, 2, 3)
sns.boxplot(data=[data['Feature1'], data_imputed['Feature1']], palette=['blue', 'orange'])
plt.xticks([0, 1], ['Original (Feature1)', 'Imputed (Feature1)'])
plt.title("Box Plot Before and After Imputation (Feature1)")

plt.subplot(2, 2, 4)
sns.boxplot(data=[data['Feature2'], data_imputed['Feature2']], palette=['green', 'red'])
plt.xticks([0, 1], ['Original (Feature2)', 'Imputed (Feature2)'])
plt.title("Box Plot Before and After Imputation (Feature2)")

# 3. 散点图对比
plt.figure(figsize=(8, 6))
sns.scatterplot(x=data['Feature1'], y=data['Feature2'], color='blue', label='Original Data', alpha=0.6)
sns.scatterplot(x=data_imputed['Feature1'], y=data_imputed['Feature2'], color='orange', label='Imputed Data', alpha=0.6)
plt.title("Scatter Plot Before and After Imputation")
plt.xlabel("Feature1")
plt.ylabel("Feature2")
plt.legend()

plt.tight_layout()
plt.show()